package com.example.jn.checkticketforandroid;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.device.ScanManager;
import android.media.MediaPlayer;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.util.Xml;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

//日志
import de.mindpipe.android.logging.log4j.LogConfigurator;

import java.io.File;

import android.os.Environment;

import com.example.zhouwei.library.CustomPopWindow;
import com.google.gson.Gson;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;


public class CheckTicketActivity extends Activity {
    NfcAdapter nfcAdapter;
    TextView iccardno;//IC卡卡号
    TextView strTicketCode;//票号
    private int type;
    private ScanManager mScanManager;
    private boolean scanPowerState;
    private boolean lockTrigglerState;
    private String barcodeStr;//二维码号码
    static String barcodeStrAgain;//二维码号码
    private String ICcardno;//二维码号码
    private TextView et_search;
    private TextView Ticketstatue;
    private TextView TicketName;
    private TextView TicketNumeber;
    private TextView TicketTime;
    String getresult;
    String mygetsoundid, mygetname, mygetstatue, mygetnumber, mygettime, Code, verifiedNum, OpenNum;
    protected final static String SCAN_ACTION = "urovo.rcv.message";//扫描结束action
    private final static String NFC_ACTION = "jason.broadcast.action";//扫描结束action


    private String url;
    private String myname;
    private String mypwd;
    private String gateno;
    private MediaPlayer mp = new MediaPlayer();

    private int iCheckNO = 0;//已检人数，退出清零
    private TextView CheckNOStr;

    /****************karl add 2018-7-3**************/
    /*public String apiKey = "ZGFtb2VkYzljNDQx";
    public String apiSecret = "ZGFtbzk3YjU0YTFjNDBjYWNhMzE=";
    public String TerminalNum = "A010103";                                                                          //配置文件获取
    public String CheckTicketUrl = "http://124.114.151.86:8765/api/openApi/facility/gate/verify";          //配置文件获取
    public String KeepAliveUrl = "http://124.114.151.86:8765/api/openApi/facility/gate/alive";             //配置文件获取*/


    public String apiKey = "";
    public String apiSecret = "=";
    public String TerminalNum = "";              //配置文件获取
    public String CheckTicketUrl = "";          //配置文件获取
    public String KeepAliveUrl = "";             //配置文件获取
    public boolean bNeedCheckTicket = true;    //检票标志位
    public TextView SysStatus;                    //系统状态
    public String strSysstatus;                   //系统状态字符串
    static Logger gLogger;                                 //日志
    private int periodCount = 1;                //默认3s检一次
    private File file;                            //定义日志存储路径


    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            //得到二维码后锁住Trigger

            if (bNeedCheckTicket) {
                bNeedCheckTicket = false;
                //清空显示
                clearTiketInfo();

                // TODO Auto-generated method stub
                byte[] barocode = intent.getByteArrayExtra("barocode");
                System.out.print(barocode);
                int barocodelen = intent.getIntExtra("length", 0);
                byte temp = intent.getByteExtra("barcodeType", (byte) 0);
                barcodeStr = new String(barocode, 0, barocodelen);

                //gLogger.debug("barcodeStr:" + barcodeStr);

                strTicketCode.setText(barcodeStr);
                if (barcodeStr != null && !barcodeStr.equals(""))//&& barcodeStrAgain != barcodeStr
                {
                    if (mCustomPopWindow != null) {
                        mCustomPopWindow.dissmiss();
                        mCustomPopWindow = null;
                    }
                    MyProgressUtils.showProgressDialog(CheckTicketActivity.this);
                    HttpURL();
                }
                //定时线程启动下次检票
                TriggerThread();
            } else {
                setSysstatus("请稍等...");
            }
        }

    };
    private CustomPopWindow mCustomPopWindow;

    //日志配置
    public void configLog() {
        final LogConfigurator logConfigurator = new LogConfigurator();

        logConfigurator.setFileName(Environment.getExternalStorageDirectory() + File.separator + "CheckTicket.log");
        // Set the root log level
        logConfigurator.setRootLevel(Level.DEBUG);
        // Set log level of a specific logger
        logConfigurator.setLevel("org.apache", Level.ERROR);
        logConfigurator.configure();

        //gLogger = Logger.getLogger(this.getClass());
        gLogger = Logger.getLogger("CrifanLiLog4jTest");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        configLog();
        gLogger.debug("程序开始");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checkticket);
        strTicketCode = (TextView) findViewById(R.id.ticketID_statusno);
        et_search = (TextView) findViewById(R.id.ticket_no);
        Ticketstatue = (TextView) findViewById(R.id.ticket_statusno);

        TicketName = (TextView) findViewById(R.id.ticket_nameno);
        TicketNumeber = (TextView) findViewById(R.id.ticket_numberno);
        TicketTime = (TextView) findViewById(R.id.ticket_timeno);
        CheckNOStr = (TextView) findViewById(R.id.iCheckNO);
        SysStatus = (TextView) findViewById(R.id.systatus);
        //*获取Intent中的Bundle对象*//*
        Bundle bundle = getIntent().getExtras();
        url = getIntent().getStringExtra("url");
        myname = getIntent().getStringExtra("myname");
        mypwd = getIntent().getStringExtra("mypwd");
        gateno = getIntent().getStringExtra("gateno");

        try {
            file = new File(Environment.getExternalStorageDirectory(), "CheckTicketConfig.ini");
            //读取配置文件(.ini)
            String Result = "";

            FileInputStream fis = null;

            byte[] buffer = null;

            try {
                fis = new FileInputStream(file);
                buffer = new byte[fis.available()];
                fis.read(buffer);
            } catch (FileNotFoundException e) {
                //e.printStackTrace();
                gLogger.debug(e);
            } catch (IOException e) {
                //e.printStackTrace();
                gLogger.debug(e);
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                        Result = new String(buffer);
                    } catch (IOException e) {
                        //e.printStackTrace();
                        gLogger.debug(e);
                    }
                }
            }

            gLogger.debug("Result:" + Result);

            JSONObject jsonobj = new JSONObject(Result);

            apiKey = jsonobj.getString("apiKey");
            apiSecret = jsonobj.getString("apiSecret");
            TerminalNum = jsonobj.getString("TerminalNum");
            CheckTicketUrl = jsonobj.getString("CheckTicketUrl");
            KeepAliveUrl = jsonobj.getString("KeepAliveUrl");
            String strTime = jsonobj.getString("Time");
            periodCount = Integer.parseInt(strTime);

            gLogger.debug("apiKey:" + apiKey);
            gLogger.debug("apiSecret:" + apiSecret);
            gLogger.debug("TerminalNum:" + TerminalNum);
            gLogger.debug("CheckTicketUrl:" + CheckTicketUrl);
            gLogger.debug("KeepAliveUrl:" + KeepAliveUrl);
            gLogger.debug("periodCount:" + periodCount);

        } catch (Exception e) {
            //e.printStackTrace();
            gLogger.debug(e);
        }

        barcodeStr = "";
        ICcardno = "";
        barcodeStrAgain = "";
        //初始化扫描器
        initScan();

        //意图过滤器和广播注册
        IntentFilter filter = new IntentFilter();
        filter.addAction(SCAN_ACTION);
        //  unregisterReceiver(mScanReceiver);
        registerReceiver(mScanReceiver, filter);


        IntentFilter filter1 = new IntentFilter();
        filter1.addAction(NFC_ACTION);

        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                //  System.out.println("卡号："+intent.getExtras().getString("data"));


                ICcardno = intent.getExtras().getString("data");
                strTicketCode.setText(ICcardno);
                if (ICcardno != null && !ICcardno.equals("")) {
                    HttpURL();
                }

            }
        };
        registerReceiver(broadcastReceiver, filter1);

        KeepAlive();
        //开始检票
        String pathsound = "/storage/sdcard0/sound/48.wav";
        play(pathsound);
    }

    //设置系统状态
    public void setSysstatus(String str) {
        strSysstatus = str;
        SysStatus.post(new Runnable() {
            @Override
            public void run() {
                SysStatus.setText(strSysstatus);
            }
        });
    }

    //清空显示
    public void clearTiketInfo() {
        strTicketCode.setText("");
        et_search.setText("");
        Ticketstatue.setText("");
        TicketName.setText("");
        TicketNumeber.setText("");
        TicketTime.setText("");
        strTicketCode.setText("");
        CheckNOStr.setText("");
    }

    //屏蔽返回键
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onPause();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

/*    @Override
    protected void onDestroy() {
        unregisterReceiver(mScanReceiver);
        unregisterReceiver(broadcastReceiver);
    }*/

    @Override
    protected void onResume() {
        super.onResume();
        //得到是否检测到ACTION_TECH_DISCOVERED触发
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
            //处理该intent
            processIntent(getIntent());
        }
    }

    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    //字符序列转换为16进制字符串
    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("0x");
        if (src == null || src.length <= 0) {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
            buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
            System.out.println(buffer);
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString();
    }

    /**
     * Parses the NDEF Message from the intent and prints to the TextView
     */
    private void processIntent(Intent intent) {
        //取出封装在intent中的TAG
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        for (String tech : tagFromIntent.getTechList()) {
            System.out.println(tech);
        }
        boolean auth = false;
        //读取TAG
        MifareClassic mfc = MifareClassic.get(tagFromIntent);
        try {
            String metaInfo = "";
            //Enable I/O operations to the tag from this TagTechnology object.
            mfc.connect();
            int type = mfc.getType();//获取TAG的类型
            int sectorCount = mfc.getSectorCount();
            //获取TAG中包含的扇区数
            String typeS = "";
            switch (type) {
                case MifareClassic.TYPE_CLASSIC:
                    typeS = "TYPE_CLASSIC";
                    break;
                case MifareClassic.TYPE_PLUS:
                    typeS = "TYPE_PLUS";
                    break;
                case MifareClassic.TYPE_PRO:
                    typeS = "TYPE_PRO";
                    break;
                case MifareClassic.TYPE_UNKNOWN:
                    typeS = "TYPE_UNKNOWN";
                    break;
            }
/*            metaInfo += "卡片类型：" + typeS + "\n共" + sectorCount + "个扇区\n共"
                    + mfc.getBlockCount() + "个块\n存储空间: " + mfc.getSize() + "B\n";*/
            for (int j = 0; j < 1 /*sectorCount*/; j++) {
                //Authenticate a sector with key A.
                auth = mfc.authenticateSectorWithKeyA(j, MifareClassic.KEY_DEFAULT);
                int bCount;
                int bIndex;

                if (auth) {
                    //  metaInfo += "Sector " + j + ":验证成功\n";
                    // 读取扇区中的块

                    bCount = mfc.getBlockCountInSector(j);
                    bIndex = mfc.sectorToBlock(j);
                    for (int i = 0; i < 1 /*bCount*/; i++) {
                        byte[] data = mfc.readBlock(bIndex);
                        /*metaInfo += "Block " + bIndex + " : "
                                + bytesToHexString(data) + "\n";*/
                        metaInfo += bytesToHexString(data) + "\n";

                        bIndex++;
                    }
                } else {
                    metaInfo += "Sector " + j + ":验证失败\n";
                }
            }
            //iccardno.setText(metaInfo.substring(2, 10));

            String getdata = metaInfo.substring(2, 10);
            getdata = getdata.substring(6, 8) + getdata.substring(4, 6) + getdata.substring(2, 4) + getdata.substring(0, 2);
            ICcardno = new BigInteger(getdata, 16).toString();
            strTicketCode.setText(ICcardno);
            if (ICcardno != null && !ICcardno.equals("")) {
                HttpURL();
            }


        } catch (Exception e) {
            e.printStackTrace();
            gLogger.debug(e);
        }
    }


    //定时器实现防连刷的功能
    public void TriggerThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                long count = 0;
                while (true) {
                    if (periodCount <= count) {
                        bNeedCheckTicket = true;
                        setSysstatus("请检票");
                        break;
                    }

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count++;
                }
            }
        }).start();
    }


    private void initScan() {
        // TODO Auto-generated method stub
        mScanManager = new ScanManager();
        type = mScanManager.getScannerType();
        switch (type) {
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                break;
        }
        scanPowerState = mScanManager.getScannerState();
        if (!scanPowerState) {
            mScanManager.openScanner();
        }
        lockTrigglerState = mScanManager.getTriggerLockState();
        if (lockTrigglerState) {
            mScanManager.unlockTriggler();
        }
        mScanManager.switchOutputMode(0);
    }


    //====================================================================接口调用
    private void HttpURL() {
/*        new Thread(){
            public void run() {
                send();
            }
        }.start();*/

        new Thread(new Runnable() {
            @Override
            public void run() {
                send();
            }
        }).start();

    }

//    public boolean send() {
//
//        try {
//            String ticketNo = barcodeStr;
//            String curTime = getTime();
//            String nonce = GetRandom(10);
//            String sign_before = "apiKey=" + apiKey + "&apiSecret=" + apiSecret
//                    + "&curTime=" + curTime + "&nonce=" + nonce;
//            String sign = SHA1.encryptToSHA(sign_before);
//            System.out.println(sign);
//
//            String sendDate = "{\"terminalNum\":\"" + TerminalNum + "\"," +
//                    "\"verifyCode\":\"" + ticketNo + "\",\"verifyType\":1}";
//            //String sendDate = "ticketNo=" + ticketNo + "&certificateNo=" + certificateNo + "&userName=" + myname + "&password=" + mypwd + "&gateNo=" + gateno + "&sign=" + sign;
//            String result = sendPost(CheckTicketUrl, sendDate, sign, nonce, curTime, apiKey);
//            System.out.println(result);
//
//            GetTicketInfo(result);
//
//            if (Code.equals("0")) {
//                //设置状态
//                Ticketstatue.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        Ticketstatue.setText(mygetstatue);
//                    }
//                });
//                //设置票名称
//                TicketName.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        TicketName.setText(mygetname);
//                    }
//                });
//
//                //票预定人数
//                if (mygetnumber.indexOf("-1") >= 0) {
//                    mygetnumber = "1";
//                }
//
//                TicketNumeber.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        TicketNumeber.setText(mygetnumber);
//                    }
//                });
//                //设置有效时间
//                TicketTime.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        TicketTime.setText(mygettime);
//                    }
//                });
//                //设置已检票人数
//                CheckNOStr.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        CheckNOStr.setText(verifiedNum);
//                    }
//                });
//                //欢迎光临
//                String pathsound = "/storage/sdcard0/sound/1.wav";
//                play(pathsound);
//
//            } else {
//                //设置状态
//                Ticketstatue.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        Ticketstatue.setText(mygetstatue);
//                    }
//                });
//
//                //设置有效时间
//                TicketTime.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        TicketTime.setText(mygettime);
//                    }
//                });
//
//               /*   42001, "订单不存在"
//                    42002, "验证码无效"),
//                    42003, "订单已过期"),
//                    42004, "订单已完成无法核销"),
//                    42005, "订单申请退款中或已退款无法核销"),
//                    42006, "当前时间不在订单有效期内，无法核销"),
//                    42007, "订单已取消无法核销"),
//                    42011, "该订单必须在下单后延迟核销"),*/
//                String playSound = "";
//
//                switch (Code) {
//                    case "42001":
//                        playSound = "/storage/sdcard0/sound/20.wav";
//                        break;
//                    case "42002":
//                        playSound = "/storage/sdcard0/sound/14.wav";
//                        break;
//                    case "42003":
//                        playSound = "/storage/sdcard0/sound/19.wav";
//                        break;
//                    case "42004":
//                        playSound = "/storage/sdcard0/sound/21.wav";
//                        break;
//                    case "42005":
//                        playSound = "/storage/sdcard0/sound/24.wav";
//                        break;
//                    case "42006":
//                        playSound = "/storage/sdcard0/sound/27.wav";
//                        break;
//                    case "42007":
//                        playSound = "/storage/sdcard0/sound/24.wav";
//                        break;
//                    default:
//                        playSound = "/storage/sdcard0/sound/22.wav";
//                }
//                play(playSound);
//            }
//
//            barcodeStr = "";
//        } catch (Exception e) {
//            showToast("连接超时，请重试！");
//            return false;
//        }
//        return true;
//    }

    public boolean send() {

        try {
            String sendUrl =  url + "checkTicketInterface/checkTicket.do";
            //String sendUrl = "http://122.4.248.213:80/checkTicketInterface/checkTicket.do";
            String ticketNo = barcodeStr;
            String certificateNo = "";
            String icCardNo = ICcardno;


            Map<String, String> map = new HashMap<String, String>();
            map.put("ticketNo", ticketNo);
            map.put("certificateNo", certificateNo);
            map.put("cardNo", icCardNo);
            map.put("userName", myname);
            map.put("password", mypwd);
            map.put("gateNo", gateno);
            String sign = buildMysign(map, "zmdjfkgudjrhkhssnh");
            System.out.println(sign);

            String sendDate = "ticketNo=" + ticketNo + "&certificateNo=" + certificateNo
                    + "&cardNo=" + icCardNo + "&userName=" + myname + "&password=" + mypwd
                    + "&gateNo=" + gateno + "&sign=" + sign;
            //String sendDate = "ticketNo=" + ticketNo + "&certificateNo=" + certificateNo + "&userName=" + myname + "&password=" + mypwd + "&gateNo=" + gateno + "&sign=" + sign;
            String result = sendPost(sendUrl, sendDate);
            System.out.println(result);

            MyProgressUtils.dismissProgress();
            //将String类型转换成json类型
            JSONObject object = null;
            try {
                object = XML.toJSONObject(result);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            String jsonData = object.toString();        //转换为json字符串。
            Log.d("", "" + jsonData);
            final CheckTicketResponse response1 = new Gson().fromJson(jsonData, CheckTicketResponse.class);

            final int status = response1.getCheckTicketMessageResult().getCode();


            switch (status) {
                case 0:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Ticketstatue.setText(response1.getCheckTicketMessageResult().getMsg());
                            TicketName.setText(response1.getCheckTicketMessageResult().getTicketName());
                            TicketNumeber.setText(String.valueOf(response1.getCheckTicketMessageResult().getTotalMaxNumber()));
                            TicketTime.setText(response1.getCheckTicketMessageResult().getCheckTime());
                            if (status == 0) {

                                iCheckNO += response1.getCheckTicketMessageResult().getTotalMaxNumber();//累加人数
                            }
                            CheckNOStr.setText(String.valueOf(iCheckNO));
                        }
                    });
                    break;
                default:
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            if (mCustomPopWindow != null) {
//                                mCustomPopWindow.dissmiss();
//                                mCustomPopWindow=null;
//                                showPopTopWithDarkBg_checked(response1);
//
//                            } else {
//                            }
                            showPopTopWithDarkBg_checked(response1);
                        }
                    });

                    break;
            }


//            String soundid = getxmlstr1(result, "gateSoundID");
            String pathsound = "/storage/sdcard0/sound/" + response1.getCheckTicketMessageResult().getGateSoundId() + ".wav";
            play(pathsound);


//            mygetstatue = getxmlstr1(result, "msg");
//            Ticketstatue.post(new Runnable() {
//                @Override
//                public void run() {
//                    Ticketstatue.setText(mygetstatue);
//                }
//            });
//            mygetname = getxmlstr1(result, "ticketName");
//            TicketName.post(new Runnable() {
//                @Override
//                public void run() {
//                    TicketName.setText(mygetname);
//                }
//            });
//            mygetnumber = getxmlstr1(result, "totalMaxNumber");
//
//            if (mygetnumber.indexOf("-1") >= 0) {
//                mygetnumber = "1";
//            }
//
//            TicketNumeber.post(new Runnable() {
//                @Override
//                public void run() {
//                    TicketNumeber.setText(mygetnumber);
//                }
//            });
//
//            mygettime = getxmlstr1(result, "checkTime");
//
//            TicketTime.post(new Runnable() {
//                @Override
//                public void run() {
//                    TicketTime.setText(mygettime);
//                }
//            });
//
//            barcodeStr = "";
//            ICcardno = "";
//
//            if (result.indexOf("<code>0</code>") > 0) {
//                iCheckNO += Integer.parseInt(mygetnumber);//累加人数
//
//                CheckNOStr.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        CheckNOStr.setText(String.valueOf(iCheckNO));
//                    }
//                });
//            }


        } catch (Exception e) {
            MyProgressUtils.dismissProgress();
            showToast("检票异常:" + e.getMessage());
            return false;
        } finally {
            MyProgressUtils.dismissProgress();
        }
        return true;
    }

    /**
     * 显示PopupWindow 同时背景变暗
     */
    private void showPopTopWithDarkBg_checked(CheckTicketResponse response1) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_checked, null);
        TextView tv_result = (TextView) contentView.findViewById(R.id.pop_checked_tv_result);
        TextView tv_ticketName = (TextView) contentView.findViewById(R.id.pop_checked_tv_ticketName);
        TextView tv_checkTime = (TextView) contentView.findViewById(R.id.pop_checked_tv_checkTime);
        TextView tv_checkTerminal = (TextView) contentView.findViewById(R.id.pop_checked_tv_checkTerminal);
        TextView tv_checkCount = (TextView) contentView.findViewById(R.id.pop_checked_tv_checkCount);
        TextView tv_saleTime = (TextView) contentView.findViewById(R.id.pop_checked_tv_saleTime);
        TextView tv_returnTime = (TextView) contentView.findViewById(R.id.pop_checked_tv_returnTime);
        TextView tv_returnCoun = (TextView) contentView.findViewById(R.id.pop_checked_tv_returnCount);
        TextView tv_startTime = (TextView) contentView.findViewById(R.id.pop_checked_tv_startTime);
        TextView tv_endTime = (TextView) contentView.findViewById(R.id.pop_checked_tv_endTime);


        tv_result.setText("" + response1.getCheckTicketMessageResult().getMsg());
        tv_ticketName.setText("" + response1.getCheckTicketMessageResult().getTicketName());
        tv_checkTime.setText("" + response1.getCheckTicketMessageResult().getCheckTime());
        tv_checkTerminal.setText("" + response1.getCheckTicketMessageResult().getTicketcheckgate());
        tv_checkCount.setText("" + response1.getCheckTicketMessageResult().getTicketcheckcount());
        tv_saleTime.setText("" + response1.getCheckTicketMessageResult().getSaletime());
        tv_returnTime.setText("" + response1.getCheckTicketMessageResult().getReturntime());
        tv_returnCoun.setText("" + response1.getCheckTicketMessageResult().getReturnsum());
        tv_startTime.setText("" + response1.getCheckTicketMessageResult().getTicketstarttime());
        tv_endTime.setText("" + response1.getCheckTicketMessageResult().getTicketendtime());


        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.5f) // 控制亮度
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        Log.e("TAG", "onDismiss");

                    }
                })
                .create()
                .showAtLocation(strTicketCode, Gravity.CENTER, 0, 0);

//                .showAsDropDown(btn3,0,20)

    }

    private void handleLogic(View contentView) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }

            }
        };
        contentView.findViewById(R.id.pop_img).setOnClickListener(listener);
    }

    public boolean GetTicketInfo(String Result) {

        boolean ret = false;
        try {
            //JSONArray jsonArray = new JSONArray(Result);
            //JSONObject jsonObject = jsonArray.getJSONObject(0);
            JSONObject jsonObject = new JSONObject(Result);
            Code = jsonObject.getString("code");

            if (Code.equals("0")) {
                JSONObject jsonObject2 = jsonObject.getJSONObject("data");
                mygetname = jsonObject2.getString("ticketName");
                mygetnumber = jsonObject2.getString("touristNum");
                verifiedNum = jsonObject2.getString("verifiedNum");
                OpenNum = jsonObject2.getString("openNum");
                String effectiveStartDate = jsonObject2.getString("effectiveStartDate");
                String effectiveEndDate = jsonObject2.getString("effectiveEndDate");
                mygettime = effectiveStartDate + "至" + effectiveEndDate;
                mygetstatue = "请通行";
                ret = true;
            } else {
                mygetstatue = jsonObject.getString("msg");
                mygettime = "";
                //订单已过期
                if (Code.equals("42003")) {
                    JSONObject jsonObject2 = jsonObject.getJSONObject("data");
                    String effectiveStartDate = jsonObject2.getString("effectiveStartDate");
                    String effectiveEndDate = jsonObject2.getString("effectiveEndDate");
                    mygettime = effectiveStartDate + "至" + effectiveEndDate;
                }
                //订单已完成无法核销
                if (Code.equals("42004")) {
                    JSONObject jsonObject2 = jsonObject.getJSONObject("data");
                    String effectiveStartDate = jsonObject2.getString("effectiveStartDate");
                    String effectiveEndDate = jsonObject2.getString("effectiveEndDate");
                    mygettime = effectiveStartDate + "至" + effectiveEndDate;
                }
                //订单申请退款中或已退款无法核销
                if (Code.equals("42005")) {
                    JSONObject jsonObject2 = jsonObject.getJSONObject("data");
                    String effectiveStartDate = jsonObject2.getString("effectiveStartDate");
                    String effectiveEndDate = jsonObject2.getString("effectiveEndDate");
                    mygettime = effectiveStartDate + "至" + effectiveEndDate;
                }

                //当前时间不在订单有效期内，无法核销
                if (Code.equals("42006")) {
                    JSONObject jsonObject2 = jsonObject.getJSONObject("data");
                    String effectiveStartDate = jsonObject2.getString("effectiveStartDate");
                    String effectiveEndDate = jsonObject2.getString("effectiveEndDate");
                    mygettime = effectiveStartDate + "至" + effectiveEndDate;
                }

                //该订单必须在下单后延迟核销
                if (Code.equals("42011")) {
                    JSONObject jsonObject2 = jsonObject.getJSONObject("data");
                    String effectiveStartDate = jsonObject2.getString("effectiveStartDate");
                    String effectiveEndDate = jsonObject2.getString("effectiveEndDate");
                    mygettime = effectiveStartDate + "至" + effectiveEndDate;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ret;
    }

    public static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }


    /**
     * 验证消息是否为合法消息
     *
     * @param params 参数数组
     * @param key    接口密钥
     * @return 验证结果
     */
    public static boolean verify(Map<String, String> params, String key) {

        String mysign = buildMysign(params, key);
        String sign = "";
        if (params.get("sign") != null) {
            sign = params.get("sign");
        }
        if (mysign.equals(sign)) {
            return true;
        } else {
            System.out.println("本地签名：" + mysign + " 远程签名：" + sign);
            return false;
        }
    }

    /**
     * 生成签名结果
     *
     * @param sArray 要签名的数组
     * @param key    通知密钥
     * @return 签名结果字符串
     */
    public static String buildMysign(Map<String, String> sArray, String key) {
        try {
            Map<String, String> result = paraFilter(sArray);
            String prestr = createLinkString(result); //把数组所有元素，按照“参数参数值”的模式拼接成字符串
            prestr = key + prestr; //把接口密钥+拼接后的字符串直接连接起来
            String mysign = md5(prestr);
            if (mysign != null) {
                mysign = mysign.toUpperCase();
                System.out.println(mysign);
            }
            return mysign;
        } catch (Exception e) {

        }
        return null;
    }

    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }


    /**
     * @param content
     * @param charset
     * @return
     * @throws UnsupportedEncodingException
     * @throwsSignatureException
     */
    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }

        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

    /**
     * 除去数组中的空值和签名参数
     *
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {
        Map<String, String> result = new HashMap<String, String>();
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }

    /**
     * 把数组所有元素排序，并按照“参数参数值”的模式拼接成字符串
     *
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            prestr = prestr + key + value;
        }
        return prestr;
    }

    //获取当前系统10位的时间戳
    public String getTime() {

        long time = System.currentTimeMillis() / 1000;//获取系统时间的10位的时间戳

        String str = String.valueOf(time);

        return str;

    }

    //获取指定位数的随机数
    public String GetRandom(int num) {
        String strRand = "";
        for (int i = 0; i < num; i++) {
            strRand += String.valueOf((int) (Math.random() * 10));
        }

        return strRand;
    }

    //开启保活线程
    public void KeepAlive() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                while (true) {
                    String ticketNo = barcodeStr;
                    String curTime = getTime();
                    String nonce = GetRandom(10);
                    String sign_before = "apiKey=" + apiKey + "&apiSecret=" + apiSecret
                            + "&curTime=" + curTime + "&nonce=" + nonce;
                    String sign = SHA1.encryptToSHA(sign_before);
                    System.out.println(sign);

                    String sendDate = "{\"terminalNum\":\"" + TerminalNum + "\"}";
                    //String sendDate = "ticketNo=" + ticketNo + "&certificateNo=" + certificateNo + "&userName=" + myname + "&password=" + mypwd + "&gateNo=" + gateno + "&sign=" + sign;
                    String result = sendPostAlive(KeepAliveUrl, sendDate, sign, nonce, curTime, apiKey);
                    System.out.println(result);

                    try {
                        Thread.sleep(1200000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param sendUrl 发送请求的 URL
     * @param param   请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
//    public static String sendPost(String sendUrl, String param, String sign, String nonce, String curTime, String apiKey) {
//        try {
//            // 发送POST请求
//            URL url = new URL(sendUrl);
//            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//            conn.setRequestMethod("POST");
//            conn.setRequestProperty("apiKey", apiKey);
//            conn.setRequestProperty("curTime", curTime);
//            conn.setRequestProperty("nonce", nonce);
//            conn.setRequestProperty("sign", sign);
//            //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//            conn.setRequestProperty("Content-Type", "application/json");
//            conn.setRequestProperty("Connection", "Keep-Alive");
//            conn.setUseCaches(false);
//            conn.setDoInput(true);
//            conn.setDoOutput(true);
//            conn.setConnectTimeout(1000 * 10);
//            conn.setReadTimeout(1000 * 20);
//
//            conn.setRequestProperty("Content-Length", "" + param.length());
//            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
//            out.write(param);
//            out.flush();
//            out.close();
//
//            // 获取响应状态
//            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
//                System.out.println("connect failed!");
//                return "";
//            }
//
//            //gLogger.debug("param:" + param);
//
//            String line, result = "";
//            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
///*            while ((line = in.readLine()) != null) {
//                result += line + "\n";
//            }*/
//            result = in.readLine();
//            //in.close();
//            return result;
//        } catch (IOException e) {
//            e.printStackTrace(System.out);
//        }
//        return "";
//    }
    public static String sendPost2(String sendUrl, String param) {
        try {
            // 发送POST请求
            URL url = new URL(sendUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
//            conn.setRequestProperty("apiKey", apiKey);
//            conn.setRequestProperty("curTime", curTime);
//            conn.setRequestProperty("nonce", nonce);
//            conn.setRequestProperty("sign", sign);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setConnectTimeout(1000 * 10);
            conn.setReadTimeout(1000 * 20);

            conn.setRequestProperty("Content-Length", "" + param.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(param);
            out.flush();
            out.close();

            // 获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }

            //gLogger.debug("param:" + param);

            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
/*            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }*/
            result = in.readLine();
            //in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return "";
    }

    public static String sendPost(String sendUrl, String param) {
        try {
            // 发送POST请求
            URL url = new URL(sendUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(1000 * 10);
            conn.setReadTimeout(1000 * 20);

            conn.setRequestProperty("Content-Length", "" + param.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(param);
            out.flush();
            out.close();

            // 获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }
            // 获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return "";
    }

    //保活功能(25分钟发送一次)
    public static String sendPostAlive(String sendUrl, String param, String sign,
                                       String nonce, String curTime, String apiKey) {
        try {
            // 发送POST请求
            URL url = new URL(sendUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("apiKey", apiKey);
            conn.setRequestProperty("curTime", curTime);
            conn.setRequestProperty("nonce", nonce);
            conn.setRequestProperty("sign", sign);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(1000 * 10);
            conn.setReadTimeout(1000 * 20);

            conn.setRequestProperty("Content-Length", "" + param.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(param);
            out.flush();
            out.close();

            // 获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }

            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return "";
    }

    private static String getString(byte[] b) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            sb.append(b[i]);
        }
        return sb.toString();
    }

    public String getxmlstr(String xml) {
        ByteArrayInputStream tInputStringStream = null;
        try {
            if (xml != null && !xml.trim().equals("")) {
                tInputStringStream = new ByteArrayInputStream(xml.getBytes());
            }
        } catch (Exception e) {
            return "";
        }
        XmlPullParser parser = Xml.newPullParser();
        try {
            parser.setInput(tInputStringStream, "UTF-8");
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
                        // persons = new ArrayList<Person>();
                        break;
                    case XmlPullParser.START_TAG:// 开始元素事件
                        String name = parser.getName();
                        if (name.equalsIgnoreCase("msg")) {

                            getresult = parser.nextText();
                            System.out.println(getresult);


                            Ticketstatue.post(new Runnable() {
                                @Override
                                public void run() {
                                    Ticketstatue.setText(getresult);
                                }
                            });

                        }
                        break;
                    case XmlPullParser.END_TAG:// 结束元素事件
                        break;
                }
                eventType = parser.next();
            }
            tInputStringStream.close();
            // return persons;

        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return "";
    }

    public String getxmlstr1(String xml, String resultstr) {
        ByteArrayInputStream tInputStringStream = null;
        String returnstr = "";
        try {
            if (xml != null && !xml.trim().equals("")) {
                tInputStringStream = new ByteArrayInputStream(xml.getBytes());
            }
        } catch (Exception e) {
            return "";
        }
        XmlPullParser parser = Xml.newPullParser();
        try {
            parser.setInput(tInputStringStream, "UTF-8");
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
                        // persons = new ArrayList<Person>();
                        break;
                    case XmlPullParser.START_TAG:// 开始元素事件
                        String name = parser.getName();
                        if (name.equalsIgnoreCase(resultstr)) {
                            returnstr = parser.nextText();
                            System.out.println(returnstr);

                        }
                        break;
                    case XmlPullParser.END_TAG:// 结束元素事件
                        break;
                }
                eventType = parser.next();
            }
            tInputStringStream.close();
            // return persons;

        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return returnstr;
    }
    //============================================================================


    //非UI线程中显示Toast
    public void showToast(String msg) {
        Looper.prepare();
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
        Looper.loop();
    }



    //播放音乐的方法
    private void play(String path) {
        try {
            mp.reset();//从新设置要播放的音乐
            mp.setDataSource(path);
            mp.prepare();//预加载音频
            //  mp= MediaPlayer.create(this, R.raw.my);
            mp.start();//播放音乐

        } catch (Exception e) {
            e.printStackTrace();
            Log.e("err", e.getMessage());
        }
        return;
    }

    //播放音乐方法二
    private void myplay() {
        try {
            mp.reset();
            mp.setDataSource("/storage/sdcard1/test.wav");
            mp.prepare();
            mp.start();

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void timer1() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                // System.out.println("-------设定要指定任务--------");
                barcodeStrAgain = "";
            }
        }, 5000);
    }

}
